package src.tree;

import java.util.ArrayDeque;
import java.util.LinkedList;

public class no101 {//对称二叉树

    public boolean isSymmetric(TreeNode root) {
        if (root == null) return true;
        return compare(root.left, root.right);
    }

    public boolean compare(TreeNode left, TreeNode right) {
        if (left == null && right == null) return true;
        else if (left == null && right != null) return false;
        else if (left != null && right == null) return false;
        else if (left.val != right.val) return false;

/*
        boolean outside = compare(left.left, right.right);//比较树的外侧，左树的左结点 和 右树的右结点
        boolean inside = compare(left.right, right.left);//比较树的内侧，左树的右结点 和 右树的左结点
        return outside && inside;
*/
            //以上逻辑可合并
        else return compare(left.left, right.right) && compare(left.right, right.left);
    }


    //迭代法，使用栈 队列都行，每次成对的取出两个元素比较，成对放入四个元素
    public boolean isSymmetric2(TreeNode root) {
        if (root == null) return true;
        LinkedList<TreeNode> stack = new LinkedList<>();
        stack.push(root.left);
        stack.push(root.right);
        while (!stack.isEmpty()) {
            TreeNode left = stack.peek();
            stack.pop();
            TreeNode right = stack.peek();
            stack.pop();
            if (left == null && right == null) continue;
            if ((left == null && right != null) || (left != null && right == null) || (left.val != right.val)) {
                return false;
            }

            stack.push(left.left);
            stack.push(right.right);
            stack.push(left.right);
            stack.push(right.left);
        }
        return true;

    }

}
